//
//  PersonViewModel.m
//  CoreData
//
//  Created by ZRAR on 16/1/18.
//  Copyright © 2016年 ZRAR. All rights reserved.
//

#import "PersonViewModel.h"
#import "Person.h"
#import "EditViewModel.h"

@interface PersonViewModel ()<NSFetchedResultsControllerDelegate>

@property (nonatomic, strong)RACSignal *updatedContentSingal;

@end


@implementation PersonViewModel


- (instancetype)initWithModel:(id)model{
    
    self = [super initWithModel:model];
    if (self) {
        
        self.updatedContentSingal = [[RACSubject subject] setNameWithFormat:@"PersonViewModelUpdataContent"];
        @weakify(self);

        [self.didBecomeActiveSignal subscribeNext:^(id x) {
            @strongify(self);
            
            [self.fetchedResultsController performFetch:nil];
        }];
        
    }
    return self;
}

- (NSInteger)numberOfSections{
    
    
    return [[self.fetchedResultsController sections]count];
}

- (NSInteger)numberOfItemsInSections:(NSInteger)section{
    id <NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section];
    
    return [sectionInfo numberOfObjects];
}

- (void)deleteObjectAtIndexPath:(NSIndexPath *)indexPath{
    
    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    [context deleteObject:object];
    NSError *error = nil;
    if ([context save:&error] == NO) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
}


- (NSString *)titleForSection:(NSInteger)section{
    
    id<NSFetchedResultsSectionInfo>sectionInfo = [self.fetchedResultsController sections][section];
    NSArray *sectionObjects = [sectionInfo objects];
    Person *person = [sectionObjects firstObject];
    
    return person.header;
}

- (NSString *)titleAtIndexPath:(NSIndexPath *)indexPath{
    
    Person *person = [self personAtIndexPath:indexPath];
    
    return person.name;
}


- (NSString *)subtitleAtIndexPath:(NSIndexPath *)indexPath{
    
    Person *person = [self personAtIndexPath:indexPath];
    
    return person.phone;
}

- (Person *)personAtIndexPath :(NSIndexPath *)indexPath{
    
    
    return [self.fetchedResultsController objectAtIndexPath:indexPath];
}

- (NSFetchedResultsController *)fetchedResultsController{
    
    if (_fetchedResultsController != nil) {
        
        return _fetchedResultsController;
    }
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.model];
    [fetchRequest setEntity:entity];
    [fetchRequest setFetchBatchSize:20];//从数据库里每次加载500条数据来筛选数据
   // [fetchRequest setFetchOffset:1];//读取数据库的游标偏移量，从游标开始读取数据
    //[fetchRequest setFetchLimit:3];//每次要去多少条数据，10就是每次从数据库读取10条数据
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    
    NSArray *sortDescriptors = @[sortDescriptor];
    [fetchRequest setSortDescriptors:sortDescriptors];
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.model sectionNameKeyPath:@"header" cacheName:@"Persons"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;
    NSError *error = nil;
    if (![self.fetchedResultsController performFetch:&error]) {
      
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _fetchedResultsController;
}


- (EditViewModel *)editViewModelForIndexPath:(NSIndexPath *)indexPath{
    
    EditViewModel *viewModel = [[EditViewModel alloc] initWithModel:[self personAtIndexPath:indexPath]];
    
    return viewModel;
}

- (EditViewModel *)editViewModelForNewPerson{
    
    Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.model];
    
    EditViewModel *viewModel = [[EditViewModel alloc] initWithModel:person];
    viewModel.inserting = YES;
    return viewModel;
    
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{

    [(RACSubject *)self.updatedContentSingal sendNext:nil];
    
}


@end
